#include "enter.h"
#include "createlist.h"
#include "perfor.h"
char username[10] = {0};
int picnum = 0;
int enter(int lcdp[][800], int *c)
{
	int cho = 30, x = 0, fx = 0, y = 0, fy = 30, flag = 1, i, j, color = b;
	printf("当前用户:%s\n", username);
	FILE *pic = fopen("./res/enter.bmp", "r");
	if (pic == NULL)
	{
		printf("enter open fail\n");
		return -1;
	}
	unsigned char buf[480][800 * 3] = {0};
	fseek(pic, 54, SEEK_SET);
	fread(buf, 3, 480 * 800, pic);
	for (i = 0; i < 480; i++)
		for (j = 0; j < 800; j++)
		{
			y = 479 - i;
			lcdp[y][j] = 0x00 << 24 | buf[i][j * 3 + 2] << 16 | buf[i][j * 3 + 1] << 8 | buf[i][j * 3];
		}
	int lcdt = open("/dev/input/event0", O_RDWR);
	if (lcdt < 0)
	{
		perror("input error\n");
		return -1;
	}
	struct input_event touch;
	while (1)
	{
		char users[20];
		font *ef = fontLoad("/usr/share/fonts/DroidSansFallback.ttf");
		fontSetSize(ef, 50);
		sprintf(users, "%s %s %s", "尊敬的用户:", username, "欢迎您的使用:)");
		bitmap *er = createBitmapWithInit(1024, 50, 4, getColor(0, 255, 255, 0));
		fontPrint(ef, er, 0, 0, users, getColor(0, 255, 0, 0), 1000);
		show_font_to_lcd(lcdp, 0, 1, er);
		int read_ret = read(lcdt, &touch, sizeof(struct input_event));
		if (read_ret < 0)
		{
			perror("read touch failed\n");
			return -1;
		}
		if (touch.type == EV_ABS)
		{
			if (touch.code == ABS_X)
				x = touch.value * 800 / 1024;
			else if (touch.code == ABS_Y)
			{
				y = touch.value * 480 / 600;
			}
		}
		printf("x=%d y=%d \n", x, y);
		if (touch.type == EV_KEY)
		{
			if (touch.code == BTN_TOUCH && touch.value == 1)
			{
				if (x > 0 && x < 80 && y > 400 && y < 480)
					return -1;
			}
			if (x > 160 && x < 360 && y > 150 && y < 330)
			{
				perfor(lcdp);
			jump:
				*c = 1;
				cho = 30;
				list *s = createlist();
				push(s, lcdp);
				while (*c != 3)
				{
					cho = pos(lcdp, s, &cho, &x, &y, &fy, &color, &flag);
					*c = cho;
					if (*c == 3)
					{
						free(s);
						goto done;
					}
				}
			}
			if (x > 440 && x < 650 && y > 145 && y < 350)
			{
				int ret = record(lcdp);
				if (ret >= 0)
				{
					perfor(lcdp);
					char filename[20];
					sprintf(filename, "./lib/%s %d.txt", username, ret);
					FILE *reco = fopen(filename, "r");
					for (i = 0; i < 480; i++)
						for (j = 0; j < 750; j++)
							if (fscanf(reco, "%d", &lcdp[i][j]) != 1)
							{
								perror("read fail\n");
								goto done;
							}
					fclose(reco);
					goto jump;
				}
				else if (ret == -1)
				{
					for (i = 0; i < 480; i++)
						for (j = 0; j < 800; j++)
						{
							y = 479 - i;
							lcdp[y][j] = 0x00 << 24 | buf[i][j * 3 + 2] << 16 | buf[i][j * 3 + 1] << 8 | buf[i][j * 3];
						}
					goto done;
				}
			}
		}
		destroyBitmap(er);
	}
done:
	close(lcdt);
	fclose(pic);
	return 1;
}